const fs = require('fs')
const path = require('path')
const cheerio = require('cheerio')
const ejs = require('ejs')

module.exports = {
  report: {
    type: 'web',
    prompts: [
      {
        label: 'APPKEY',
        desc: '创建应用时提供的应用 APPKEY',
        name: 'appKey',
        type: 'string',
        required: true
      },
      {
        label: '上报地址',
        desc: '部署运营系统后的上报地址',
        name: 'report_url',
        type: 'string',
        required: true
      },
      {
        label: '自动上报 PV',
        desc: '创建应用时提供的应用 APPKEY',
        name: 'autoReportPv',
        type: 'boolean',
        initialValue: true
      },
      {
        label: '用户自定义属性',
        desc: '用户自定义的额外属性',
        name: 'customUserPrams',
        type: 'array',
        'x-component': 'table',
        children: [
          {
            label: 'key',
            name: 'key',
            type: 'string'
          },
          {
            label: 'value',
            name: 'value',
            type: 'string'
          }
        ]
      }
    ],
    action: ({ projectPath, data, logger }) => {
      logger.log('运营配置 Action 数据', data)
      // dev-html 不上报
      const htmlFilePath = path.join(projectPath, 'public', 'index.html')
      const $ = cheerio.load(
        fs.readFileSync(htmlFilePath, {
          encoding: 'utf8'
        })
      )

      // 模版替换
      const ejsRenderTemplate = `
        if (yyptReport && typeof (yyptReport.pgvMain) == 'function') {
          yyptReport.pgvMain({
            report_url: <$$- JSON.stringify(data.report_url) $$>,
            appKey: <$$- JSON.stringify(data.appKey) $$>,
            autoReportPv: <$$- JSON.stringify(data.autoReportPv) $$>,
            customUserPrams: {
              <$$ data.customUserPrams.forEach(item => { $$>
                <$$= item.key $$>: <$$- JSON.stringify(item.value) $$>,
              <$$ }) $$>
            },
          });
        }
      `

      // 重写配置
      const renderContent = ejs.render(
        ejsRenderTemplate,
        {
          data
        },
        {
          delimiter: '$$'
        }
      )
      $('#TTools__report').html(renderContent)
      fs.writeFileSync(htmlFilePath, $.html(), {
        encoding: 'utf8'
      })
    }
  }
}
